<?php
class Comment_AjaxController extends Clu_Controller_Action_Hvn
{
	public $m, $mPlace, $mArticle;
	
	public function init()
	{
		//require_once (APP_PATH.'/modules/place/Model/Place.php');
//		require_once (APP_PATH.'/modules/article/Model/Article.php');
		
		$this->mPlace = new place_Model_Place();
		$this->mArticle = new article_Model_Service();
		$this->m = new comment_Model_Service();
		$this->mUser = new user_Model_User();
//		$this->mNodes = new comment_Model_NodeService();
		parent::init();
	}
	
	public function newCommentAction()
	{
		
//		die($view->hvnUrl(array('module' => 'node', 'action' => 'new'),'nocontroller'));
		$sess = new Zend_Session_Namespace(CLU_NS);
		$db = $this->db;
		$form = new comment_Form_Comment();
		$actionUrl = "/" .$sess->viewLang . "/comment/ajax/new-comment";
        $form->cluBuild(array('action' => 'new', 
        						'action_url' => $actionUrl, 
        						'control' => 'ajax', 
        						'content_type' => $this->_request->getParam('content_type'),
        						'region' => $this->_request->getParam('region'),
                                //'userPermissions' => $sess->userPermissions,
                                'language' => $sess->viewLang ));
        $postData = $this->_request->getParams();
		if($this->_request->isXmlHttpRequest() && $form->isValid($_POST))
		{	
			$ret = array();
			if (empty($postData['comment_text']))
			{
				$ret = array("success" => false, "errorMessage" => "Click again");
				$this->_helper->json->sendJson($ret);
				
			}	
			if($this->m->insertRaw($postData, false))
			{
		    //update comments for comment table and insert this comments to comments table by user ID
			    $sql = "UPDATE nodes SET comments = comments + 1 WHERE id =".$this->_request->getParam('content_id')."";
			    $db->query($sql);
			    $ret['success'] =  true;
				$ret['id'] = $this->db->lastInsertId();
				$data = $this->m->findByPrimary($ret['id']);
				$ret['comment_body'] = $data['comment_text'];
				
				//send mail alert to user
				$this->sendAlertMail($postData['content_poster_id'],$postData['poster_id'],$postData);
			}
			else
			{
				$ret['success'] =  false;
				$ret['errorMessage'] = "DB error";
				$this->_helper->json->sendJson($ret);
			}
		}
		else
		{
		 	$ret['errorMessage'] = t(71);
		 	$ret['success'] = false;
		}	
		$this->_helper->json->sendJson($ret);  
	}
	
	public function sendAlertMail($contentPosterId,$posterId,$data)
	{
		//initialize view object and add Help path so that hvnUrl can be called
		$view = $this->view;
		$view->addHelperPath(
            APP_PATH . '/library/Clu/View/Helper',
            'Clu_View_Helper'
        );
        $view->setScriptPath(APP_PATH . '/'); 
        
		if($contentPosterId != $posterId)
		{
			$user1 = $this->mUser->findByPrimary($contentPosterId);
			$user2 = $this->mUser->findByPrimary($posterId);
			$link = "<a href='http://herevietnam.vn".$this->view->hvnUrl(array('type' => $data['type'], 'action' => 'view'), 'node')."?id=".$data['content_id'].
					"'>http://herevietnam.vn".$this->view->hvnUrl(array('type' => $data['type'], 'action' => 'view'), 'node')."?id=".$data['content_id']."</a>";
			$subject = $user2->name." write a comment in your post:<br/><br/>";
			$mailBody = $user2->name." write a comment in your post:<br/><br/>\"".
			$data['comment_text']."\"<br/><br/><br/><br/>View comments,please click link below:<br/>";
			$this->mNodeService = new node_Model_NodeService();
			$nodeTypeInfo = $this->mNodeService->getNodeTypeInfo('pm');
			$this->mNodeService->mNode->setNodeTableName($nodeTypeInfo['node_table_name']);
			$dataPM = array('receiver_id' => $contentPosterId, 'poster_id' => $posterId,
						  'title' => $subject, 'body' => $mailBody, 'created' => time(), 
						  'poster_category' => 0, 'receiver_category' => 0, 'type_id' => 4,
						  'title_is_reply' => 0, ' flag' => 0,
						);
			
			$this->mNodeService->insertNewNode($dataPM, $nodeTypeInfo);
			
//			if(isset($data['type']) && $data['type'] != 'place' && $data['type'] != 'event' && $data['type'] != 'user')
//				$mailBody .= $link;
			$mailBody .= "'><br/><br/>Thank you !";
			$mailer = new Clu_Mail_HvnMailer();
			$mailer->sendMail($user1->mail, $subject, $mailBody);
		}
		else
        	return;
        	
	}
	
	public function deleteCommentAction()
	{
    	$id = $this->_request->getParam('id');
    	$posterId = $this->_request->getParam('poster_id');
    	$contentPosterId = $this->_request->getParam('content_poster_id');
    	$contentType = $this->_request->getParam('content_type');
    	
    	if($this->_request->isXmlHttpRequest())
		{
			$db = $this->db;
    	    $ret = array();
    	    
    	    //check permission
    	    $sess = new Zend_Session_Namespace(CLU_NS);
    	                 
    	    if($sess->userId == $posterId && strpos($sess->userPermissions, 'delete own comment') ||  //commenter
	         		strpos($sess->userPermissions, 'delete comment') || //comment admin
	         		$sess->userId == $contentPosterId || //content owner TODO
	         		strpos($sess->userPermissions, 'administer ' . $contentType))
			{
	    	    $sql = "SELECT id,content_id FROM comments WHERE pid=".$db->quote($id, 'STRING');
	    	    $text = $db->fetchAll($sql);
	    	    foreach($text as $t)
	    	    {
	    	    	$ret['child']= array( 'childId' => $t['id']);
	    	    }
	            if ($this->m->deleteByPrimary(array($id), true) )
	            {
	            	$sql = "UPDATE nodes SET comments = comments -1 WHERE id =".$this->_request->getParam('content_id')."";
			        $db->query($sql);
	            	$ret['success'] = true;
	            }
	            else
	            	$ret['success'] = false;
	            	 
				$this->_helper->json->sendJson($ret);
			}
		    else
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
		}
	}
	
	public function editCommentAction() 
	{
//		die_a($this->_request->getParams());
		$id = $this->_request->getParam('id'); 
		$statusComment = $this->_request->getParam('status') ;
		$textComment   = $this->_request->getParam('comment_text') ;
		$titleComment  = $this->_request->getParam('title') ;
		if ($this->_request->isXmlHttpRequest() )
		{
		    $db = $this->db;
		    $ret = array();
		    $sql = "UPDATE comments SET ";
		    if($statusComment != null) 
		    	$sql.= " status=".$db->quote($statusComment, 'STRING') ;
		    if($textComment != null)
		    	$sql.= " comment_text=".$db->quote($textComment, 'STRING').',title ='.$db->quote($titleComment, 'STRING');
		    $sql.= " WHERE id=".$db->quote($id, 'INTEGER');
		    try {
	           	$db->query($sql);
			    $ret['success'] = true;
		    }
		    catch (Exception $e)
		    {
		    	$ret['success'] = false;
		    }
		    $ret['id'] = $id;
		    $ret['status'] 		 = $statusComment;
			$ret['comment_text'] = $textComment;
		    $this->_helper->json->sendJson($ret);
		}
	}
	
	public function updateRatingAction() 
	{
		$id = $this->_request->getParam('id'); 
		$rating = $this->_request->getParam('rate');
		$auth = Zend_Auth::getInstance();
		if ($this->_request->isXmlHttpRequest())
		{
		    $db = $this->db;
		    $ret = array();
		    
		    //update rating for comment table and insert this rating to ratings table by user ID
		    $sql1 = "UPDATE comments SET rating=".$db->quote($rating, 'INTEGER').",rating_count = rating_count +". $db->quote($rating, 'INTEGER') ." WHERE id=".$db->quote($id, 'INTEGER');
		    $sql2 = "INSERT INTO ratings (rater_id ,content_id) VALUES (" .$auth->getIdentity()->id. "," . $id. ")";
		    try {
	           	$db->query($sql1);
           	  	$db->query($sql2);
			    $ret['success'] = true;
		    }
		    catch (Exception $e)
		    {
		    	$ret['success'] = false;
		    }
		    $ret['id'] = $id;
		    $ret['rate'] = $rating;
			$this->_helper->json->sendJson($ret);
		}
	}
	
	/**
	 * Search by 'place' or 'article', or 'user' module
	 */
	public function searchByModuleAction()
	{
		if ($this->_request->isXmlHttpRequest())
		{
			$ret = array();
			try {
	           	$select = $this->m->search($this->_request->getParams());
        		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        		$paginator->setItemCountPerPage($this->_request->getParam('comments_per_page'));
        		$paginator->setCurrentPageNumber($this->_request->getParam('page_number'));
        		Zend_Paginator::setDefaultScrollingStyle('Jumping');
        		$this->view->paginator = $paginator;
        		$this->view->cList  = $paginator->getCurrentItems();
			    $ret['success'] = true;
	           	$ret['commentList'] = $this->view->render('en/index/commentList.phtml');
		    }
		    catch (Exception $e)
		    {
		    	$ret['success'] = false;
		    }
			$this->_helper->json->sendJson($ret);
		}
	}
	public function searchChildrenAction()
	{
		if ($this->_request->isXmlHttpRequest())
		{	
			try {
	           	$select = $this->m->searchChildrenList($this->_request->getParams());
        		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        		$paginator->setCurrentPageNumber($this->_request->getParam('page_number'));
        		$paginator->setItemCountPerPage(2);
        		Zend_Paginator::setDefaultScrollingStyle('Jumping');
        		$this->view->paginator = $paginator;
        		$this->view->pid = $this->_request->getParam('id');
        		$this->view->cList  = $paginator->getCurrentItems();
        		$ids = array();
	           	//die($paginator);
        		foreach ($this->view->cList as $c)
        			$ids[] = $c['id'];
			    $ret['success'] = true;
	           	$ret['commentList'] = $this->view->render('en/index/childList.phtml');
	           	$ret['ids'] = $ids;
		    }
		    catch (Exception $e)
		    {
		    	$ret['success'] = false;
		    }
			$this->_helper->json->sendJson($ret);
		}
	}
	
	public function bulkCommentAction()
    {	
    	if($this->_request->isXmlHttpRequest())
		{
        	$ids = $this->_request->getParam('comment_ids');
        	//check permission
        	$sess = new Zend_Session_Namespace(CLU_NS);
		    if (strpos ($sess->userPermissions, 'administer user') === false)
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
			
        	$ret['ids'] = $ids;
        	if (count($ids) > 0)
        	{
            	$action = $this->_request->getParam('bulkaction');
                if ($action === 'delete')
                {
                    if ($this->m->deleteByPrimary($ids))
    					$ret['success'] = true;
                }
                else if($action === 'status')
            	{
                	$ret['status'] = $this->_request->getParam('changestatus');
    				if ($this->m->bulkUpdateStatus($ids, $ret))
    				  	$ret['success'] = true;       
                }
        	}
        	else
        		$ret['success'] = false;
        	$ret['bulkaction'] = $action;
        	$this->_helper->json->sendJson($ret);
		}
    }
}	
?>
